package com.hb.back.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import com.hb.common.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
@RequestMapping("/oss")
@Tag(name = "oss阿里云上传")
public class OssController {
    @Value("${ali.endpoint}")
    private String endpoint;
    @Value("${ali.bucketName}")
    private String   bucketName ;
    @Value("${ali.accessKeyId}")
    private String accessKeyId;
    @Value("${ali.secretAccessKey}")
    private String secretAccessKey;

    @PostMapping("/{type}")
    @Operation(summary = "阿里云上传")
    public ResultVo addFile(@PathVariable String type, MultipartFile file) throws ClientException {
        if (file.isEmpty()){
            return ResultVo.error("文件不能为空","");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName= UUID.randomUUID().toString().replace("-","")+substring;
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "zxjy-ondemand";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt
        String objectName=type+"/"+fileName;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        String filePath="E:\\QQ文件\\springboot在线教育考试素材+试卷\\素材（图片和视频）\\springboot课程体系介绍.mp4";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,secretAccessKey);
        try{
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            String path=endpoint+"/"+type+"/"+fileName;
            System.out.println(path);
            return ResultVo.success("上传阿里云成功!",path);
        }catch (OSSException oe) {
            return ResultVo.error("上传阿里云失败!",null);
        }finally {
            if(ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
